from django.views.generic import TemplateView
from accounts.utils.data_analysis import SurveyAnalyzer
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Line, Radar
from pyecharts.globals import ThemeType
import random


class ReligiousAnalysisView(TemplateView):
    template_name = 'charts/religious_analysis.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        analyzer = SurveyAnalyzer()
        religions = analyzer.analyze_religions()

        # 创建宗教信仰柱状图
        religion_data = religions['religion_dist']
        religion_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis([k.replace('dist_', '') for k in religion_data.keys()])
            .add_yaxis("人数", list(religion_data.values()))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="宗教信仰分布"),
                xaxis_opts=opts.AxisOpts(name="宗教类型"),
                yaxis_opts=opts.AxisOpts(name="人数")
            )
        )
        context['religion_chart'] = religion_bar.render_embed()

        # 添加原始数据到上下文
        context['religion_data'] = {k.replace('dist_', ''): v for k, v in religion_data.items()}

        # 创建宗教信仰占比饼图
        religion_pie = (
            Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add(
                "",
                [list(z) for z in zip(
                    [k.replace('dist_', '') for k in religion_data.keys()],
                    list(religion_data.values())
                )],
                radius=["30%", "70%"],
                label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="宗教信仰比例"),
                legend_opts=opts.LegendOpts(orient="vertical", pos_left="left")
            )
        )
        context['religion_pie_chart'] = religion_pie.render_embed()

        # 模拟不同年龄段的宗教信仰分布数据
        age_groups = ['12-15岁', '16-18岁', '19-22岁', '23-25岁']
        religions_list = [k.replace('dist_', '') for k in religion_data.keys()][:5]  # 取前5个宗教类型

        # 模拟每个年龄段的宗教信仰分布数据
        age_religion_data = {}
        for religion in religions_list:
            age_religion_data[religion] = [
                random.randint(10, 100) for _ in range(len(age_groups))
            ]

        # 创建不同年龄段的宗教信仰分布柱状图
        age_religion_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(age_groups)
        )

        for religion, values in age_religion_data.items():
            age_religion_bar.add_yaxis(religion, values)

        age_religion_bar.set_global_opts(
            title_opts=opts.TitleOpts(title="不同年龄段宗教信仰分布"),
            xaxis_opts=opts.AxisOpts(name="年龄段"),
            yaxis_opts=opts.AxisOpts(name="信仰人数"),
            legend_opts=opts.LegendOpts(orient="horizontal", pos_top="top")
        )
        context['age_religion_chart'] = age_religion_bar.render_embed()

        # 模拟宗教信仰与社交活跃度关系数据
        social_activity = ['低社交活跃', '中等社交活跃', '高社交活跃', '极高社交活跃']
        religion_social_data = {}
        for religion in religions_list:
            religion_social_data[religion] = [
                random.randint(10, 100) for _ in range(len(social_activity))
            ]

        # 创建宗教信仰与社交活跃度关系折线图
        social_line = (
            Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(social_activity)
        )

        for religion, values in religion_social_data.items():
            social_line.add_yaxis(religion, values, is_smooth=True)

        social_line.set_global_opts(
            title_opts=opts.TitleOpts(title="宗教信仰与社交活跃度关系"),
            xaxis_opts=opts.AxisOpts(name="社交活跃度"),
            yaxis_opts=opts.AxisOpts(name="信仰人数"),
            legend_opts=opts.LegendOpts(orient="horizontal", pos_top="top")
        )
        context['social_religion_chart'] = social_line.render_embed()

        # 模拟宗教信仰影响因素雷达图数据
        influence_factors = ['家庭影响', '同伴影响', '学校教育', '媒体接触', '个人探索', '社区环境']
        religion_influence_data = {}

        for religion in religions_list[:3]:  # 选择前3个宗教类型以保持图表清晰
            religion_influence_data[religion] = [
                random.randint(30, 90) for _ in range(len(influence_factors))
            ]

        # 创建宗教信仰影响因素雷达图
        radar_chart = (
            Radar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=factor, max_=100) for factor in influence_factors
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.1)
                ),
            )
        )

        for religion, values in religion_influence_data.items():
            radar_chart.add(
                religion,
                [values],
                linestyle_opts=opts.LineStyleOpts(width=2)
            )

        radar_chart.set_global_opts(
            title_opts=opts.TitleOpts(title="宗教信仰影响因素分析"),
            legend_opts=opts.LegendOpts(selected_mode='multiple')
        )
        context['religion_influence_chart'] = radar_chart.render_embed()

        # 添加分析洞察
        context['religion_insights'] = [
            {
                "title": "青少年宗教信仰多样化趋势",
                "content": "调查数据显示，青少年的宗教信仰呈现多元化趋势，不同年龄段的信仰分布存在明显差异。这反映了当代社会文化多元性对青少年精神世界的影响。"
            },
            {
                "title": "宗教信仰与社交活跃度相关性",
                "content": "数据表明，不同宗教信仰的青少年在社交活跃度方面表现出不同特点，这可能与宗教活动提供的社交场所和机会有关。"
            },
            {
                "title": "家庭影响在宗教信仰形成中的关键作用",
                "content": "研究发现，家庭环境和父母的宗教态度对青少年宗教信仰的形成起着决定性作用，是最主要的影响因素之一。"
            },
            {
                "title": "宗教信仰与青少年心理健康",
                "content": "有研究表明，拥有稳定宗教信仰的青少年通常表现出更好的心理适应能力和抗压能力，这与宗教提供的精神支持和社区归属感有关。"
            }
        ]

        context['navname'] = 'religious'

        return context
